package com.duoqin.common.utils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.duoqin.chat.Chat;
import com.duoqin.chat.ui.ChatAbsActivity;
import com.duoqin.feedback.ui.FeedbackMain;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.util.Auth;

import org.json.JSONObject;

import java.io.File;

public class QNHelper {
    private static QNHelper sQNInstance;
    private final UploadManager uploadManager;
    private Handler mHandler;

    public static QNHelper getsQNInstance(Handler handler){
        if(sQNInstance == null){
            sQNInstance = new QNHelper(handler);
        }

        return sQNInstance;
    }

    private QNHelper(Handler handler){
        mHandler = handler;
        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);
    }

    /**
     *
     * @param file file对象
     * @param  chat
     * @param key key表示在七牛存储的文件的名字
     * @return
     */
    public void uploadFile(File file, final Chat chat, String key){
        String token = generateToken();
        uploadManager.put(file, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if(info.isOK()) {
                            Log.i("Duoqin.qiniu", "Upload Success");
                            Message message = new Message();
                            message.what = ChatAbsActivity.MSG_UPLOAD_MEDIA_SUCCESS;
                            message.obj = chat;
                            mHandler.sendMessage(message);
                        } else {
                            Log.i("Duoqin.qiniu", "Upload Fail");
                            Message message = new Message();
                            message.what = ChatAbsActivity.MSG_UPLOAD_MEDIA_FAIL;
                            message.obj = chat;
                            mHandler.sendMessage(message);
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
//                        Log.d("Duoqin.qiniu", key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, null);
    }

    /**
     *
     * @param file file对象
     * @param key key表示在七牛存储的文件的名字
     * @return
     */
    public void uploadFeedbackFile(final File file, String key){
        String token = generateToken();
        Log.d("Duoqin.qiniu", "uploadFile: token = " + token);
        Log.d("Duoqin.qiniu", "uploadFile: file = " + file.getName());
        uploadManager.put(file, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if(info.isOK()) {
                            Log.i("Duoqin.qiniu", "Upload Success");
                            Message message = new Message();
                            message.what = FeedbackMain.HANDLER_UPLOAD_FILE_SUCCESS;
                            message.obj = info;
                            mHandler.sendMessage(message);
                        } else {
                            Log.i("Duoqin.qiniu", "Upload Fail");
                            Message message = new Message();
                            message.what = FeedbackMain.HANDLER_UPLOAD_FILE_FAIL;
                            message.obj = info;
                            mHandler.sendMessage(message);
                        }
//                        file.delete();
                    }
                }, null);
    }

    private String generateToken() {
        String accessKey = "sJFqRtotftfX0dBQlJAoSluhh04iTQgD6UXEB3jp";
        String secretKey = "xe6JYKSzmBRByTBmldB_6JRDD0rExSbhehYqCtbL";
        String bucket = "mqtt-wechat-voice";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(bucket);
    }
}
